<template>
  <div class="app-container">
    <div style="display: block">
      选择公司:
      <el-select v-model="project_id" v-loading="listLoading" placeholder="请选择" @change="handleSelectChange()">
        <el-option
          v-for="item in data"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <div v-if="project !== null">
        <el-descriptions class="margin-top" title="公司信息" :column="1" :size="mini" border>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user" />
              名称
            </template>
            <span>{{ project.name }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-link" />
              钉钉
            </template>
            <span>{{ project.dingding_alert_link }}</span>
          </el-descriptions-item>
        </el-descriptions>

      </div>
    </div>
    <div>
      <el-table :data="company_users" border fit highlight-current-row>
        <el-table-column
          prop="username"
          label="用户名"
        />
        <el-table-column
          prop="last_name"
          label="姓"
        >
          <template slot-scope="scope">
            {{ scope.row.last_name + scope.row.first_name }}
          </template>
        </el-table-column>
        <el-table-column
          prop="is_manager"
          label="管理员"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_manager"
              active-text="是"
              inactive-text="否"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleSetProjectUserInTable(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          align="right"
        >
          <template slot="header" slot-scope="scope">
            <el-input
              v-model="filterKeyword"
              style="width: 300px"
              size="mini"
              placeholder="输入关键字搜索"
            />
            <el-button
              size="mini"
              @click="handleAdd"
            >添加用户</el-button>
          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleModifyGroup(scope.row)"
            >编辑权限</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDeleteProjectUser(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :visible.sync="addUserDialogVisible" title="选择用户">
      <div style="margin-top: 15px;">
        <el-input v-model="searchQuery" placeholder="请输入内容" class="input-with-select">
          <el-button slot="append" :loading="searchLoading" icon="el-icon-search" @click="querySearchAsync" />
        </el-input>
      </div>
      <div style="margin-top: 20px;">
        <el-row v-for="user in filterusers" :key="user.id" class="selected-user" align="middle" style="margin-bottom: 5px">
          <el-col :span="18">
            {{ user.username }} ({{ user.last_name + user.first_name }})
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleAddSpecificUser(user)">添加</el-button>
          </el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="showUserGroupsVisible" title="用户权限" width="80%" top="5vh">
      <div class="grid-content bg-white" style="display: flex; gap: 20px; height: 70vh;">
        <!-- 左侧权限设置区域 -->
        <div style="flex: 1; overflow-y: auto; padding-right: 10px;">
          <el-row>
            <span style="display: block; font-weight: bold; margin-bottom: 10px;">系统功能模块权限</span>
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckGroupChange">全选
            </el-checkbox>
            <div v-loading="usergrouploading" style="margin: 15px 0;">
              <!-- 用户权限区域 -->
              <div v-if="userGroups.length > 0" class="permission-group">
                <div class="permission-group-title" style="color: #409EFF;">
                  <i class="el-icon-user" /> 用户权限 (User)
                </div>
                <el-checkbox-group v-model="checkedGroups" @change="handleCheckedGroupChange">
                  <div class="permission-checkbox-group">
                    <el-checkbox
                      v-for="group in userGroups"
                      :key="group.id"
                      :label="group.id"
                      :value="group.id"
                      class="permission-checkbox"
                      @change="handlePermissionHover(group.name)"
                    >
                      {{ group.name }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>

              <!-- 管理员权限区域 -->
              <div v-if="managerGroups.length > 0" class="permission-group">
                <div class="permission-group-title" style="color: #F56C6C;">
                  <i class="el-icon-user-solid" /> 管理员权限 (Manager)
                </div>
                <el-checkbox-group v-model="checkedGroups" @change="handleCheckedGroupChange">
                  <div class="permission-checkbox-group">
                    <el-checkbox
                      v-for="group in managerGroups"
                      :key="group.id"
                      :label="group.id"
                      :value="group.id"
                      class="permission-checkbox"
                      @change="handlePermissionHover(group.name)"
                    >
                      {{ group.name }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>

              <!-- 特殊权限区域 -->
              <div v-if="specialGroups.length > 0" class="permission-group">
                <div class="permission-group-title" style="color: #E6A23C;">
                  <i class="el-icon-medal" /> 特殊权限 (Special)
                </div>
                <el-checkbox-group v-model="checkedGroups" @change="handleCheckedGroupChange">
                  <div class="permission-checkbox-group">
                    <el-checkbox
                      v-for="group in specialGroups"
                      :key="group.id"
                      :label="group.id"
                      :value="group.id"
                      class="permission-checkbox"
                      @change="handlePermissionHover(group.name)"
                    >
                      {{ group.name }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>

              <!-- 其他权限区域 -->
              <div v-if="otherGroups.length > 0" class="permission-group">
                <div class="permission-group-title" style="color: #909399;">
                  <i class="el-icon-more" /> 其他权限 (Others)
                </div>
                <el-checkbox-group v-model="checkedGroups" @change="handleCheckedGroupChange">
                  <div class="permission-checkbox-group">
                    <el-checkbox
                      v-for="group in otherGroups"
                      :key="group.id"
                      :label="group.id"
                      :value="group.id"
                      class="permission-checkbox"
                      @change="handlePermissionHover(group.name)"
                    >
                      {{ group.name }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
            </div>
          </el-row>
        </div>

        <!-- 右侧权限说明区域 -->
        <div style="flex: 1; border-left: 1px solid #EBEEF5; padding-left: 20px; overflow-y: auto;">
          <div class="permission-help">
            <h3 style="margin-top: 0; color: #409EFF;">
              <i class="el-icon-question" /> 权限功能说明
            </h3>
            <div class="permission-help-content">
              <el-collapse v-model="activePermissionTab" accordion>
                <el-collapse-item
                  v-for="(moduleData, moduleName) in permissionModules"
                  :key="moduleName"
                  :name="moduleName"
                  :title="moduleData.title"
                >
                  <div class="permission-module-content">
                    <div class="permission-description">
                      <strong>模块说明：</strong>{{ moduleData.description }}
                    </div>
                    <div class="permission-roles">
                      <strong>权限角色：</strong>
                      <el-tag
                        v-for="role in moduleData.roles"
                        :key="role"
                        size="small"
                        type="info"
                        style="margin-right: 5px; margin-bottom: 5px;"
                      >
                        {{ role }}
                      </el-tag>
                    </div>
                    <div class="permission-features">
                      <strong>包含功能：</strong>
                      <ul>
                        <li v-for="feature in moduleData.features" :key="feature">
                          {{ feature }}
                        </li>
                      </ul>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </div>
      </div>
      <div style="padding: 10px 20px; border-top: 1px solid #EBEEF5; margin-top: 20px;">
        <el-divider>职能权限</el-divider>
        <el-row>
          <el-switch
            v-model="user.is_manager"
            active-text="管理员"
            inactive-text="普通用户"
            title="修改管理员权限"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleSetProjectUser"
          />
        </el-row>
        <el-divider>用户参数</el-divider>
        <el-row style="margin-top: 10px">
          <span style="display: block">用户配置</span>
          <el-form v-loading="profilelistLoading" :model="profile" label-position="left" label-width="120px">
            <el-form-item label="电话">
              <el-input v-model="profile.phone" />
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="handleModifyUserProfile">修改</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Get } from '@/api/erp/elicink/project.js'
import { fetch_users, fetch_groups, moidfy_user_profile, modify_user_groups, fetch_user_profile, modify_project_users, add_project_user, delete_project_user, ModifyProjectuser } from '@/api/manage/projectuser.js'
import qs from 'qs'

export default {
  name: 'Projectuser',
  data() {
    return {
      searchQuery: '',
      searchLoading: false,
      select_user_id: '',
      filterusers: [],
      showUserGroupsVisible: false,
      addUserDialogVisible: false,
      newCheckedUsers: [],
      project: null,
      data: [],
      listLoading: true,
      profilelistLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 100,
      page: 1,
      total: 0,
      project_id: '',

      checkAll: false,
      checkedUsers: [],
      checkedManagers: [],
      company_users: [],
      users: [],
      profile: {
        'pk': '',
        'phone': ''
      },
      groups: [],
      checkedGroups: [],
      checkedUser: '',
      user: {},
      isIndeterminate: true,
      usergrouploading: false,
      filterKeyword: '',
      activePermissionTab: 'cms',
      permissionModules: {
        'cms': {
          title: '📄 内容管理',
          description: '负责网站内容的创建、编辑、发布和管理',
          roles: ['cms_user', 'cms_manager'],
          features: [
            '编辑和发布文章',
            '管理图片和媒体资源',
            '内容工厂自动生成',
            'WordPress目录管理',
            '知识库管理',
            '流量统计分析',
            '三方账户管理',
            '公司网站管理'
          ]
        },
        'crm': {
          title: '🤖 AI智能SOP + B2B订单',
          description: '人工智能驱动的标准作业程序和B2B业务管理',
          roles: ['ai_model_user', 'ai_model_b2b_user', 'ai_model_seo_user', 'ai_model_manager', 'crm_user', 'crm_manager', 'crm_product', 'finance_user'],
          features: [
            'B2B业务流程管理',
            '独立站SEO优化',
            'SOP流程管理',
            '询盘和订单管理',
            '内部工单处理',
            '客户池管理',
            '邮件营销',
            '产品目录管理',
            '供应商管理',
            '财务管理'
          ]
        },
        'chatbot': {
          title: '🤖 AI销售机器人',
          description: 'AI驱动的智能销售和客服机器人系统',
          roles: ['chatbot_user'],
          features: [
            '向量知识库管理',
            'WhatsApp账号管理',
            '聊天机器人配置',
            '自动消息发送',
            '客户对话管理'
          ]
        },
        'landing': {
          title: '📄 落地页',
          description: '营销落地页的设计、创建和管理',
          roles: ['landing_page_user'],
          features: [
            '落地页模板管理',
            '落地页编辑器',
            '页面发布和管理',
            '转化率跟踪'
          ]
        },
        'leads': {
          title: '🔍 数据清洗',
          description: '客户数据的挖掘、清洗和分析',
          roles: ['tablestore_user', 'whatsapp_manager'],
          features: [
            '客户线索数据挖掘',
            '数据统计分析',
            '领英用户查询',
            'WhatsApp用户管理',
            '数据表格存储'
          ]
        },
        'static': {
          title: '🌐 静态网站',
          description: '静态网站的构建和管理',
          roles: ['static_site_user'],
          features: [
            '网站管理',
            '模板管理',
            '分类管理',
            '页面管理',
            '静态资源管理'
          ]
        },
        'orders': {
          title: '📊 广告营销',
          description: '广告投放和营销数据的管理与分析',
          roles: ['orders_user', 'orders_manager'],
          features: [
            '订单查询管理',
            '销售统计分析',
            '广告预算管理',
            '搜索词分析',
            'GMC产品管理',
            '跟踪单号管理',
            '报告分析',
            '热销产品统计'
          ]
        },
        'service': {
          title: '💬 客服',
          description: '客户服务和沟通管理',
          roles: ['message_user'],
          features: [
            '站内消息管理',
            '邮件收发',
            '客户投诉处理',
            '回复模板管理',
            '邮箱账号管理',
            '客户沟通记录'
          ]
        },
        'server': {
          title: '🖥️ 站点&服务器',
          description: '服务器和网站基础设施管理',
          roles: ['server_manager'],
          features: [
            '服务器状态监控',
            '网站目录管理',
            'VMware虚拟机管理',
            '访问IP管理',
            '服务器连接管理'
          ]
        },
        'spider': {
          title: '🕷️ 内容挖掘',
          description: '网络内容的搜索和挖掘',
          roles: ['spider_user'],
          features: [
            'Top内容搜索',
            '内容详情分析',
            '挖掘规则管理',
            '竞争对手分析'
          ]
        },
        'tools': {
          title: '🛠️ 工具',
          description: '各种实用工具和辅助功能',
          roles: ['erp_user'],
          features: [
            '网站库管理',
            'Best Seller分析',
            '图片合并工具',
            'SERP分析',
            '批量搜索',
            '代理管理'
          ]
        },
        'crawl': {
          title: '🔄 抓取产品',
          description: '产品信息的抓取和管理',
          roles: ['crawl_user', 'product_customer'],
          features: [
            '关键词抓取',
            'URL批量抓取',
            '竞品分析',
            '产品优化',
            '目录管理',
            'Feed管理',
            '产品浏览',
            '违禁产品管理'
          ]
        },
        'manage': {
          title: '⚙️ 系统管理',
          description: '系统的配置和管理功能',
          roles: ['admin'],
          features: [
            '公司管理',
            '用户权限管理',
            '角色权限配置',
            'Prompts管理',
            '系统配置'
          ]
        }
      }
    }
  },
  computed: {
    // 用户权限分组
    userGroups() {
      return this.groups.filter(group =>
        group.name.includes('_user') &&
          !group.name.includes('_manager') &&
          !this.isSpecialGroup(group.name)
      )
    },
    // 管理员权限分组
    managerGroups() {
      return this.groups.filter(group =>
        group.name.includes('_manager')
      )
    },
    // 特殊权限分组（admin, 独立功能等）
    specialGroups() {
      return this.groups.filter(group =>
        this.isSpecialGroup(group.name)
      )
    },
    // 其他权限分组
    otherGroups() {
      return this.groups.filter(group =>
        !group.name.includes('_user') &&
          !group.name.includes('_manager') &&
          !this.isSpecialGroup(group.name)
      )
    }
  },
  created() {
    this.project_id = this.$route.query.project_id
    console.log(this.project_id)
    if (this.project_id) {
      this.getProject()
    }
    this.getList()
  },
  methods: {
    // 判断是否为特殊权限组
    isSpecialGroup(name) {
      const specialKeywords = ['admin', 'crawl_', 'spider_', 'out_writer', 'product_customer']
      return specialKeywords.some(keyword => name.includes(keyword))
    },
    // 处理权限悬停/点击事件
    handlePermissionHover(permissionName) {
      // 根据权限名称找到对应的模块
      const moduleMapping = {
        'cms_user': 'cms',
        'cms_manager': 'cms',
        'ai_model_user': 'crm',
        'ai_model_b2b_user': 'crm',
        'ai_model_seo_user': 'crm',
        'ai_model_manager': 'crm',
        'crm_user': 'crm',
        'crm_manager': 'crm',
        'crm_product': 'crm',
        'finance_user': 'crm',
        'chatbot_user': 'chatbot',
        'landing_page_user': 'landing',
        'tablestore_user': 'leads',
        'whatsapp_manager': 'leads',
        'static_site_user': 'static',
        'orders_user': 'orders',
        'orders_manager': 'orders',
        'message_user': 'service',
        'server_manager': 'server',
        'spider_user': 'spider',
        'erp_user': 'tools',
        'crawl_user': 'crawl',
        'product_customer': 'crawl',
        'admin': 'manage'
      }

      const moduleKey = moduleMapping[permissionName]
      if (moduleKey) {
        this.activePermissionTab = moduleKey
      }
    },
    handleSetProjectUser() {
      ModifyProjectuser({ project_id: this.project_id, user_id: this.user.id, is_manager: this.user.is_manager }).then((response) => {
        this.$message({
          message: '修改成功',
          type: 'success'
        })
      }).catch(err => {
        console.error('修改失败:', err)
      })
    },
    handleSetProjectUserInTable(user) {
      ModifyProjectuser({ project_id: this.project_id, user_id: user.id, is_manager: user.is_manager }).then((response) => {
        this.$message({
          message: '管理员权限修改成功',
          type: 'success'
        })
      }).catch(err => {
        console.error('修改失败:', err)
        // 如果修改失败，恢复原来的状态
        user.is_manager = !user.is_manager
        this.$message({
          message: '修改失败，请重试',
          type: 'error'
        })
      })
    },
    handleModifyUserProfile() {
      this.profile['pk'] = this.checkedUser
      moidfy_user_profile(this.profile).then((response) => {
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
        this.listLoading = false
      }).catch(error => {
        this.$notify({
          title: '失败',
          message: '修改失败',
          type: 'error',
          duration: 2000
        })
        this.listLoading = false
        console.log(error)
      })
    },
    handleCheckedGroupChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.users.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.users.length
      this.usergrouploading = true
      modify_user_groups(JSON.stringify({
        pk: this.checkedUser,
        groups: this.checkedGroups
      })).then((response) => {
        this.checkedGroups = response.data.checkedGroups
        this.groups = response.data.groups
        this.$message({
          message: '修改成功',
          type: 'success'
        })
        this.usergrouploading = false
      }).catch(error => {
        console.log(error)
        this.usergrouploading = false
      })
    },
    handleCheckedUserChange() {
      this.profilelistLoading = true
      this.groups = []
      this.checkedGroups = []
      fetch_groups(JSON.stringify({ pk: this.checkedUser })).then((response) => {
        this.checkedGroups = response.data.checkedGroups
        this.groups = response.data.groups
        this.profilelistLoading = false
      }).catch(error => {
        this.profilelistLoading = false
        console.log(error)
      })
      this.handleFetch_user_profile()
    },
    handleFetch_user_profile() {
      this.profile = {
        'pk': this.checkedUser,
        'phone': ''
      }
      fetch_user_profile(JSON.stringify({ pk: this.checkedUser })).then((response) => {
        if (response.data) {
          this.profile.phone = response.data.phone
        } else {
          this.profile.phone = ''
        }

        console.log(this.profile)
        this.listLoading = false
      }).catch(error => {
        this.listLoading = false
        console.log(error)
      })
    },
    handleCheckGroupChange(val) {
      this.listLoading = true
      fetch_groups(JSON.stringify({ pk: this.checkedUser })).then((response) => {
        this.checkedGroups = response.data.checkedGroups
        this.groups = response.data.groups
        this.listLoading = false
      }).catch(error => {
        this.listLoading = false
        console.log(error)
      })
      this.handleFetch_user_profile()
    },
    handleAddSpecificUser(user) {
      add_project_user({ project_id: this.project_id, user_id: user.id, is_manager: user.is_manager }).then((response) => {
        this.company_users = response.data.company_users
        this.addUserDialogVisible = false
      }).catch(err => {
        console.error('添加失败:', err)
      })
    },
    handleModifyGroup(user) {
      this.showUserGroupsVisible = true
      this.checkedUser = user.id
      this.user = user
      this.handleCheckedUserChange()
    },
    handleDeleteProjectUser(user) {
      delete_project_user({ project_id: this.project_id, user_id: user.id }).then((response) => {
        this.company_users = response.data.company_users
      }).catch(err => {
        console.error('删除失败:', err)
      })
    },
    querySearchAsync() {
      if (this.searchQuery) {
        this.searchLoading = true
        fetch_users({ project_id: this.project_id, kw: this.searchQuery }).then((response) => {
          this.filterusers = response.data.users.map(user => ({
            value: user.username + ' (' + user.last_name + ' ' + user.first_name + ')',
            id: user.id,
            username: user.username,
            first_name: user.first_name,
            last_name: user.last_name
          }))
          this.searchLoading = false
        }).catch(err => {
          console.error('搜索失败:', err)
          this.searchLoading = false
        })
      }
    },
    handleSelectUser(item) {
      this.newCheckedUsers.push(item)
    },
    handleAdd() {
      this.newCheckedUsers = []
      this.addUserDialogVisible = true
    },
    getProject() {
      Get(this.project_id).then(response => {
        this.project = response.data
        this.target_web_id = this.project_id
        this.handleSelectChange()
        console.log(this.project)
      }).catch(err => {
        console.log(err)
      })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.total = response.data.total
          this.listLoading = false
        })
        .catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleSelectChange() {
      fetch_users({ project_id: this.project_id }).then((response) => {
        this.company_users = response.data.company_users
        this.users = response.data.users
      }).catch(error => {
        console.log(error)
      })
    },
    handleCheckAllManager(val) {
      console.log(this.users.map(function(item) {
        return item.id
      }))
      this.checkedManagers = val ? this.users.map(function(item) {
        return item.id
      }) : []
      this.isIndeterminate = false
    },
    handleCheckAllChange(val) {
      console.log(this.users.map(function(item) {
        return item.id
      }))
      this.checkedUsers = val ? this.users.map(function(item) {
        return item.id
      }) : []
      this.isIndeterminate = false
    },
    handlecheckedUsersChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.users.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.users.length
      modify_project_users(JSON.stringify({
        project_id: this.target_web_id,
        users: this.checkedUsers,
        checkedManagers: this.checkedManagers
      })).then((response) => {
        this.checkedUsers = response.data.selectedUsers
        this.users = response.data.users
        console.log(this.users)
      }).catch(error => {
        console.log(error)
      })
    }
  }
}
</script>

<style scoped>
.permission-group {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #FAFAFA;
}

.permission-group-title {
  display: flex;
  align-items: center;
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 14px;
}

.permission-group-title i {
  margin-right: 5px;
}

.permission-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.permission-checkbox {
  margin-right: 15px;
  margin-bottom: 10px;
  padding: 5px 10px;
  border: 1px solid #E4E7ED;
  border-radius: 4px;
  background-color: white;
  transition: all 0.3s;
}

.permission-checkbox:hover {
  border-color: #409EFF;
  background-color: #F0F9FF;
}

.permission-help {
  height: 100%;
}

.permission-help-content {
  max-height: 60vh;
  overflow-y: auto;
}

.permission-module-content {
  padding: 10px 0;
}

.permission-description {
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 1.5;
}

.permission-roles {
  margin-bottom: 10px;
}

.permission-features ul {
  margin: 5px 0;
  padding-left: 20px;
}

.permission-features li {
  margin-bottom: 5px;
  font-size: 13px;
  line-height: 1.4;
}

.el-dialog__body {
  padding: 20px;
}

.permission-checkbox {
  cursor: pointer;
  user-select: none;
}

.permission-checkbox:checked {
  background-color: #E6F7FF;
  border-color: #409EFF;
}
</style>
